#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import subprocess
import logging
import platform

# 如果是ptyhon2，则需要设置默认编码为utf-8
if sys.version_info.major == 2:
    reload(sys) 
    sys.setdefaultencoding('utf-8')

author_list = {}

MARKDOWN_CONTENT = ''

# 获得最新的git tag列表，按照时间排序
def get_lastest_tag(path, tag_prefix):
    
    global MARKDOWN_CONTENT

    abs_path = os.path.abspath(os.path.join(cwd, sys.argv[1], path))
    os.chdir(abs_path)
    
    if not os.path.exists(os.path.join(abs_path, '.git')):
        return ''

    # 获得最新的git tag列表，按照时间排序
    git_log_process = subprocess.Popen('git tag --sort=-creatordate', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    # 如果是windows系统
    git_tag_list = git_log_process.stdout.readlines()

    # 取得以FF.00开头的最新tag
    lastest_tag = ''
    for tag in git_tag_list:
        if tag.startswith(tag_prefix):
            lastest_tag = tag.strip()
            break

    # 如果没有以FF.00开头的tag，则退出
    if lastest_tag == '':
        return ''

    return lastest_tag

def get_changelog(path, start_tag, end_tag = 'HEAD', gitlab_url = ''):
    
    global MARKDOWN_CONTENT

    abs_path = os.path.abspath(os.path.join(cwd, sys.argv[1], path))    
    os.chdir(abs_path)

    if gitlab_url == '':
        git_url_process = subprocess.Popen('git remote get-url origin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        gitlab_url = git_url_process.stdout.readline().strip().replace('.git', '')
    else:
        gitlab_url = gitlab_url + path + '/'

    # 获得start_tag和end_tag之间的commit列表，并指定编码为utf-8
    git_log_process = subprocess.Popen('git log {}..{} --pretty="%an|%ai|%H|%s" --no-merges'.format(start_tag, end_tag), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    # 如果是windows系统
    git_log_list = git_log_process.stdout.readlines()

    MARKDOWN_CONTENT += "\n### {} \n\n_({} --> {})_\n\n".format(path, start_tag, end_tag)

    print_table_title = False
    # 提取%aN的数值
    for item in git_log_list:
        
        if platform.system() == 'Windows':
            item = item.encode('gbk')

        if '|' not in item:
            continue

        item = item.replace(' +0800', '').strip()
        items = item.split('|')

        if print_table_title == False:
            MARKDOWN_CONTENT += "| 提交信息 | 提交者 | 提交日期 | 哈希值 |\n"
            MARKDOWN_CONTENT += "| :---: | :---: | :---: | :--- |\n"

        print_table_title = True

        author = items[0].strip()
        datetime = items[1].strip()

        hash = items[2].strip()
        hash_url = '[{}]({}/commit/{})'.format(hash[:8], gitlab_url, hash)
        item = item.replace(hash, hash_url)

        log = items[3].strip()

        MARKDOWN_CONTENT += '| {} | {} | {} | {} |\n'.format(log, author, datetime, hash_url)

        module_info = "{}|{}|{}".format(path, start_tag, end_tag)
        if author in author_list.keys():
            if module_info not in author_list[author].keys():
                author_list[author][module_info] = [item]
            else:
                author_list[author][module_info].append(item)
        else:
            author_list[author] = { module_info: [item] }

    MARKDOWN_CONTENT += '\n'

    # 生成changelog
    changelog = ''
    for commit in git_log_list:
        changelog += commit

    return changelog

if '__main__' == __name__:

    try:
        MARKDOWN_CONTENT += '# 变更履历\n\n'
        MARKDOWN_CONTENT += '## 按照库进行分组\n\n----\n'

        cwd = os.getcwd()
        igitchg_path = os.path.abspath(os.path.dirname(sys.argv[0]))
        print ('cwd: {}'.format(cwd))
        print ('igitchg_path: {}\n'.format(igitchg_path))

        gitlab_url = ''
        argc = len(sys.argv)
        if argc == 3:
            # 如果提供了3个参数，则 lastest tag --> now
            start_tag = 'LATEST_TAG'
            end_tag = 'HEAD'
        elif argc == 4:
            # 如果提供了4个参数，则 argv[3] --> now
            start_tag = sys.argv[3]
            end_tag = 'HEAD'
        elif argc == 5:
            # 如果提供了5个参数，则 argv[3] --> argv[4]
            start_tag = sys.argv[3]
            end_tag = sys.argv[4]
        elif argc == 6:
            # 如果提供了6个参数，则 argv[3] --> argv[4], argv[5]是gitlab的url
            start_tag = sys.argv[3]
            end_tag = sys.argv[4]
            gitlab_url = sys.argv[5]
        else:
            print('Usage: python changelog.py <path> <tag_prefix> [start_tag] [end_tag] (gitlab_base_url)')
            sys.exit(1)
            
        print('start_tag: {}'.format(start_tag))
        print('end_tag: {}'.format(end_tag))
        print('gitlab_url: {}\n'.format(gitlab_url))

        # 删除'changelog_{}_{}.html'.format(start_tag,end_tag))
        site_dir = os.path.join(os.path.dirname(sys.argv[0]), 'site/')
        if os.path.exists(site_dir):
            import shutil
            shutil.rmtree(site_dir)

        # 获得上层目录的全部子目录
        subdirs = os.listdir(os.path.join(cwd, sys.argv[1]))
        for subdir in subdirs:

            abs_path = os.path.abspath(os.path.join(cwd, sys.argv[1], subdir))
            if os.path.isdir(abs_path) == False or os.path.exists(os.path.join(abs_path, '.git')) == False:
                print("Skip path:" + abs_path)
                continue

            print("Process path:" + abs_path)

            # 获得changelog
            if start_tag == 'LATEST_TAG':
                start_tag = get_lastest_tag(subdir, sys.argv[2])
            elif end_tag == 'LATEST_TAG':
                end_tag = get_lastest_tag(subdir, sys.argv[2])
                
            get_changelog(subdir, start_tag, end_tag, gitlab_url)
                    
        # 输出author_list
        MARKDOWN_CONTENT += '\n## 按照提交者进行分组\n\n----\n'

        for author in author_list:
            MARKDOWN_CONTENT += "\n### " + author + "\n\n"
            MARKDOWN_CONTENT += "| 提交信息 | 库 | 提交日期 | 哈希值 |\n"
            MARKDOWN_CONTENT += "| :--- | :---: | :---: | :---: |\n"
            for module in author_list[author]:
                for item in author_list[author][module]:
                    items = item.split('|')
                    datetime = items[1].strip()
                    hash = items[2].strip()
                    log = items[3].strip()

                    MARKDOWN_CONTENT += "| {} | {} | {} | {} |\n".format(log, module.split("|")[0], datetime, hash)

        
        with open(os.path.join(igitchg_path, 'docs/index.md'), 'w') as f:
            f.write(MARKDOWN_CONTENT)

        # 执行mkdocs build
        os.chdir(igitchg_path)
        subprocess.call('mkdocs build', shell=True)

    except Exception as e:
        logging.exception(e)